<template>
  <div id="app-container">
    <div class="filter-container">
      <el-button
        type="primary"
        size="middle"
        @click="handleCreate"
      >Create</el-button>
      <el-input
        v-model="listQuery.name"
        placeholder="title"
        style="width: 300px; margin-left: 20px"
        @keyup.enter.native="handleSearch"
      />
      <el-button type="primary" class="filter-button" @click="handleSearch">Search</el-button>
      <el-button type="success" class="filter-button" @click="handleExport">Export</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Name">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="XH">
        <template slot-scope="scope">
          {{ scope.row.xh }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="SFZ">
        <template slot-scope="scope">
          {{ scope.row.sfz }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Email">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Phone">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Address">
        <template slot-scope="scope">
          {{ scope.row.address }}
        </template>
      </el-table-column>
      <el-table-column label="Action" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpate(row)"
          >Edit</el-button>
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(row, $index)"
          >Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"
    />
    <!-- Edit dialog -->
    <el-dialog :visible.sync="dialogVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules">
        <el-form-item label="Name" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="XH" prop="xh">
          <el-input v-model="temp.xh" />
        </el-form-item>
        <el-form-item label="SFZ" prop="sfz">
          <el-input v-model="temp.sfz" />
        </el-form-item>
        <el-form-item label="Email" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="Phone" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="Address" prop="address">
          <el-input v-model="temp.address" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="danger"
          @click="dialogVisible = false"
        >Cancel</el-button>
        <el-button
          type="success"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getList, updateFormData, createStudent } from '@/api/student'
import pagination from '@/components/Pagination'
export default {
  components: { pagination },
  data() {
    const IDRule = (rule, value, callback) => {
      const reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      if (this.temp.sfz === '' || this.temp.sfz === 'undefine') {
        callback(new Error('resident ID is required'))
      } else if (!reg.test(this.temp.sfz)) {
        callback(new Error('wrong format'))
      } else {
        callback()
      }
    }
    return {
      total: 0,
      list: null,
      listLoading: false,
      exportLoading: false,
      // show eidt dialog ?
      dialogVisible: false,
      temp: {
        id: null,
        name: '',
        xh: '',
        sfz: '',
        email: '',
        phone: '',
        address: ''
      },
      // search condition
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      // create or edit
      dialogStatus: '',
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }],
        xh: [
          { required: true, message: 'xh is required', trigger: 'blur' },
          { min: 8, max: 8, message: 'length of xh should be 8', trigger: 'blur' }
        ],
        sfz: [{ validator: IDRule, trigger: 'blur', required: true }],
        email: [{ type: 'email', required: true, message: 'please check your email address', trigger: 'blur' }],
        phone: [{ required: true, message: 'phone number is required', trigger: 'blur' }],
        address: [{ required: true, message: 'address is required', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      // send request and recieve data from backend
      getList(this.listQuery).then((response) => {
        this.list = response.data.items
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // when user click on edit butoon, show edit dialog
    handleUpate(row) {
      this.temp = Object.assign({}, row)
      this.dialogVisible = true
      this.dialogStatus = 'update'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      this.list.splice(index, 1)
      this.$notify({
        title: 'Success',
        message: 'Delete success',
        type: 'success',
        duration: 2000
      })
    },
    // Handle create record method
    handleCreate() {
      this.restTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random * 100) + 1024
          createStudent(this.temp).then(res => {
            this.list.unshift(this.temp)
            this.dialogVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create success',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleSearch() {
      this.listQuery.page = 1
      this.fetchData()
    },
    restTemp() {
      this.temp = {
        id: null,
        name: '',
        xh: '',
        sfz: '',
        email: '',
        phone: '',
        address: '',
        // create or edit
        dialogStatus: ''
      }
    },
    // confirm update data
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // send upate request
          updateFormData(tempData).then(res => {
            // finde index of data
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogVisible = false
            this.$notify({
              title: 'Success',
              message: 'Upate success',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleExport() {
      this.exportLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const theader = ['id', 'name', 'xh', 'sfz', 'email', 'phone', 'address']
        const filterVal = ['id', 'name', 'xh', 'sfz', 'email', 'phone', 'address']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: theader,
          data,
          filename: 'student-list'
        })
        this.exportLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    }
  }
}
</script>
<style scoped>
.filter-container {
  padding: 5px;
}
.filter-button {
  padding-left: 20px;
}
</style>
